<template>
  <div>
    <!-- 面包屑导航 -->
    <breadcrumb></breadcrumb>
    <div class="main">
      <el-tabs v-model="activeName" class="mainTabs" >
        <el-tab-pane label="车队列表" name="first">
          <div class="main_item">
            <div class="control">
              <!-- 车牌号 -->
              <div class="inputItem">
                <div class="title">车队名称</div>
                <div class="inputBox">
                  <el-input v-model="fleetName" @keyup.enter.native="getList(1)">
                  </el-input>
                </div>
              </div>
              <!-- 查询 -->
              <el-button type="primary" size="small" icon="el-icon-search" @click="getList(1)">查询</el-button>
              <el-button type="plain" size="small" icon="el-icon-refresh-right" @click="CleanUp">清空</el-button>
              <div class="Btn_grounp">
                <el-button class="searchBtn" style="margin-left: 0px" type="primary" size="small" icon="el-icon-plus"
                  @click="addFleetDialog('新建车队')">新建</el-button>
              </div>
            </div>
            
            <div class="list">
              <el-table :data="records" style="width: 100%" ref="table1">
                <el-table-column align="center" prop="SerialNumber" label="序号">
                  <template slot-scope="scope">
                    {{ scope.$index+ 1 + Number(pageSize) * (pageCurrent - 1) }}
                  </template>
                </el-table-column>
                <el-table-column prop="fleetName" label="车队名称"> </el-table-column>
                <el-table-column align="center" prop="region" label="所属地区">
                </el-table-column>
                <el-table-column align="center" prop="vehicleNum" label="车辆数">
                </el-table-column>
                <el-table-column align="center" prop="driverNum" label="司机数">
                </el-table-column>
                <el-table-column align="center" prop="dispatcherName" label="负责人">
                </el-table-column>
                <el-table-column align="center" prop="dispatcherPhone" label="负责人电话">
                </el-table-column>
                <el-table-column align="center" prop="createTime" label="创建时间">
                </el-table-column>
                <el-table-column align="center" label="操作">
                  <template slot-scope="scope">
                    <div>
                      <el-button type="text" size="small" @click="
                        $router.push({
                          path: '/home/fleetManagement/details',
                          query: { fleetId: scope.row.fleetId },
                        })
                        ">详情</el-button>
                      <el-button @click="emitFleetDialog('编辑车队', scope.row.fleetId)" type="text"
                        size="small">编辑</el-button>
                      <el-button type="text" size="small" @click="deleteFleet(scope.row.fleetId)">删除</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 分页 -->
            <div class="paginationBox">
              <el-pagination @current-change="changePages($event)" class="pagination" background
                layout="slot,prev, pager, next,jumper" :total="data.total * 1" :page-size="data.size * 1"
                :pager-count="5">
                <template slot>
                  <span style="
                color: #686868;
                font-size: 12px;
                margin-right: 20px;
                display: inline-block;
              ">共{{ data.total }}条,每页{{ data.size }}条</span>
                </template>
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="授权车队列表" name="fleet">
          <consentFleet></consentFleet>
        </el-tab-pane>
        <el-tab-pane label="外部车队列表" name="external">
          <external></external>
        </el-tab-pane>
        <el-tab-pane label="司机申请加入" name="second">
          <applyJoin></applyJoin>
        </el-tab-pane>
        <el-tab-pane label="司机离开确认" name="third">
          <leaveConfirm></leaveConfirm>
        </el-tab-pane>
       
      </el-tabs>
    </div>


    <!-- 详情 -->
    <el-dialog class="supplier_Zdydialog" :title="dialogTitle" :visible.sync="visibleAddBox" width="618px">
      <el-form class="addFleetFormStyle" ref="addFleetForm" :model="addFleetForm" :rules="addFleetRules"
        label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车队名称" prop="fleetName">
              <el-input v-model="addFleetForm.fleetName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属地区" prop="region">
              <el-cascader :filter-method="filterMethod" class="zdy_cascader" ref="cityCascader" v-model="regionId"
                :options="newCity" @change="regionChange($event)" placeholder="不限" clearable :filterable="true">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="addFleetForm.address" @focus="isShowMap()"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务范围" prop="serverRange">
              <el-input v-model="addFleetForm.serverRange"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="dispatcherName">
              <el-input v-model="addFleetForm.dispatcherName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人电话" prop="dispatcherPhone">
              <el-input v-model="addFleetForm.dispatcherPhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="dialog_BtnGroup" style="margin-top: 120px">
          <el-button class="cancelBtn" @click="visibleAddBox = false">取 消</el-button>
          <el-button class="submitBtn" type="primary" @click="SubmitAudit('addFleetForm')">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog title="地址搜索" class="map_dialog" :visible.sync="VisibleMap" width="500px">
      <div class="mapBox">
        <div class="addMapBox">
          <iframe class="map" src="/orderMap.html" ref="iframe" frameborder="0" marginheight="0" marginwidth="0"
            scrolling="no"></iframe>
        </div>
        <div style="display: flex; justify-content: flex-end; margin-left: auto">
          <el-button class="cancelBtn" @click="VisibleMap = false">取 消</el-button>
          <el-button class="submitBtn" type="primary" @click="addsearchAddress()">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import breadcrumb from "@/components/breadcrumb.vue";
import newCity from "@/common/newCity";
import httpApi from "@/http";
import applyJoin from './fleetListChildren/applyJoin.vue';
import external from './fleetListChildren/external.vue';

import leaveConfirm from './fleetListChildren/leaveConfirm.vue';
import consentFleet from './fleetListChildren/consentFleet.vue'
export default {
  data() {
    //车队名称唯一校验
    let validateFleetName = (rule, value, callback) => {
      let params = {};
      if (this.fleetId) {
        params = {
          fleetName: this.addFleetForm.fleetName,
          fleetId: this.fleetId,
        };
      } else if (!this.fleetId) {
        params = {
          fleetName: this.addFleetForm.fleetName,
        };
      }

      httpApi.fleetManagementApi.FleetNameAudit(params).then((res) => {
        ////console.log('校验', res);
        if (res.data.code == 200) {
          callback(); //通过不传值
        } else if (res.data.code == 202) {
          callback(new Error("已存在")); //callback()传了参数字段就代表校验不通过
        }
      });
    };
    return {
      activeName: "first",
      dialogTitle: "",
      fleetName: "", //车队名称
      fleetId: "", //存放id用与编辑的时候使用
      visibleAddBox: false,
      VisibleMap: false,
      newCity: [],
      TypeSelected: "", //当前选择 车型
      stateSelected: "",
      records: [], //列表数据
      data: {
        total: "",
        size: "",
        pages: "",
      },
      pageCurrent: 1, //当前页
      pageSize: "10", //每页10条
      cityNumber: [], //存放城市id的数组
      regionId: [], //所属地区id 级联选择器 绑定value
      //新增车队 表单
      addFleetForm: {
        serverRange: "", //服务范围
        region: "", //所属地区  //接口要求字符 转一下
        address: "", ///地址
        fleetName: "", //车队名称
        dispatcherName: "", //负责人姓名
        dispatcherPhone: "", //负责人电话
        cityNumber: "",
        lat: "",
        lng: "",
      },
      //新增车队 表单验证规则
      addFleetRules: {
        fleetName: [
          { required: true, message: "不能为空", trigger: "blur" },
          { validator: validateFleetName, trigger: "blur" },
        ],
        region: [{ required: true, message: "不能为空", trigger: "blur" }], //所属地区 汉字字符串
        dispatcherName: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        dispatcherPhone: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        lnt: [{ required: true, message: "不能为空", trigger: "blur" }],
        lat: [{ required: true, message: "不能为空", trigger: "blur" }],
        cityNumber: [{ required: true, message: "不能为空", trigger: "blur" }], //所属地区  id字符串
      },
    };
  },
  methods: {
    // getSerialNumber() {
    //   // 前端解决序号
    //   this.records.forEach((item, i) => {
    //     let num = i + 1+Number(this.pageSize) * (this.pageCurrent - 1)
    //     item.SerialNumber = num;
    //   });
    // },
    getList(current) {
      let params = {
        portAddress: "SUPPLIER",
        fleetName: this.fleetName,
        current: current || this.pageCurrent,
        size: this.pageSize,
      };
      ////console.log(params);
      httpApi.fleetManagementApi.getFleetList(params).then((res) => {
        this.records = res.data.data.records;
        this.data = res.data.data;
        ////console.log('列表数据', this.data);
      });
    },
    addFleetDialog(dialogTitle) {
      this.dialogTitle = dialogTitle;
      this.addFleetForm = {
        serverRange: "", //服务范围
        region: "", //所属地区  //接口要求字符 转一下
        address: "", ///地址
        fleetName: "", //车队名称
        dispatcherName: "", //负责人姓名
        dispatcherPhone: "", //负责人电话
        cityNumber: "",
        lat: "",
        lng: "",
      };
      this.fleetId = "";
      this.regionId = [];
      this.visibleAddBox = true;
    },
    emitFleetDialog(dialogTitle, fleetId) {
      this.fleetId = fleetId;
      this.dialogTitle = dialogTitle;
      this.visibleAddBox = true;

      httpApi.fleetManagementApi.getFleetDetails({ fleetId }).then((res) => {
        ////console.log('获取详情,编辑回填', res);
        if (res.data.code == 200) {
          const {
            fleetName,
            region,
            address,
            dispatcherName,
            serverRange,
            dispatcherPhone,
            cityNumber,
            lat,
            lng,
          } = res.data.data;
          this.addFleetForm.address = address;
          this.addFleetForm.serverRange = serverRange;
          this.addFleetForm.fleetName = fleetName;
          this.addFleetForm.region = region;
          this.addFleetForm.dispatcherName = dispatcherName;
          this.addFleetForm.dispatcherPhone = dispatcherPhone;
          this.addFleetForm.cityNumber = cityNumber;
          this.addFleetForm.lat = lat;
          this.addFleetForm.lng = lng;

          this.regionId = cityNumber.split(",");
          ////console.log('13123', this.addFleetForm);
        }
      });
    },

    //
    SubmitAudit(formName) {
      ////console.log('新建车队总表单', this.addFleetForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.fleetId.length != 0) {
            this.addFleetForm.fleetId = this.fleetId;
            httpApi.fleetManagementApi
              .updataFleet(this.addFleetForm)
              .then((res) => {
                ////console.log('编辑车队结果', res);
                if (res.data.code == 200) {
                  this.$message.success("编辑车队成功");
                  this.getList();
                  this.visibleAddBox = false;
                } else {
                  this.$message.error("编辑车队失败");
                }
              });
          } else if (this.fleetId.length == 0) {
            httpApi.fleetManagementApi
              .addFleet(this.addFleetForm)
              .then((res) => {
                ////console.log('新增车队结果', res);
                if (res.data.code == 200) {
                  this.$message.success("新建车队成功");
                  this.getList();
                  this.visibleAddBox = false;
                } else {
                  this.$message.error("新建车队失败");
                }
              });
          }
        } else {
          return false;
        }
      });
    },

    // 搜索地区时,
    filterMethod(node, keyword) {
      if (node.text.indexOf(keyword) != -1) {
        ////console.log('node', node);
        return node.label;
      }
      //////console.log('keyword',keyword);
    },
    regionChange(val) {
      ////console.log(val);
      // 把得到的数组转为字符传
      if (val.length != 0) {
        this.region = val;
        // getNodeByValue	获取选中的节点信息

        // this.$refs.cityCascader.getCheckedNodes()[0]这方法手动点击级联选择器 可以获取节点信息, 搜索选取的 则拿不到节点信息

        var labelArr =
          this.$refs["cityCascader"].panel.getNodeByValue(val).pathLabels;

        //////console.log('getNodeByValue',labelArr);

        let idArr = this.$refs["cityCascader"].panel.getNodeByValue(val).path;
        this.addFleetForm.cityNumber = idArr.join(",");
        this.addFleetForm.region = labelArr.join("/");
        ////console.log('loaction', this.addFleetForm.region);
      } else if (val.length == 0) {
        this.addFleetForm.region = "";
      }
    },

    isShowMap(index, PlaceLabel, ItemIndex) {
      this.VisibleMap = true;
      //存放序号
      /*   this.ItemIndex = ItemIndex
        this.PlaceLabel = PlaceLabel
        this.index = index */
    },

    deleteFleet(fleetId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          httpApi.fleetManagementApi.deleteFleet({ fleetId }).then((res) => {
            ////console.log('删除结果', res);
            if (res.data.code == 200) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 回填地址信息到输入框  通过存放的序号 找到输入框回填数据
    addsearchAddress() {
      let mood = this.$refs.iframe.contentWindow.ToManualRoamFunc();

      ////console.log('ToManualRoamFunc', mood);
      localStorage.getItem("fleetAddressInfoItem", JSON.stringify(mood));

      ////console.log('拿到了吗', JSON.parse(localStorage.getItem('fleetAddressInfoItem')));
      if (!localStorage.getItem("fleetAddressInfoItem")) {
        this.$message.error("请搜索选择地址信息");
        return;
      }

      const { lat, lng, address } = JSON.parse(
        localStorage.getItem("fleetAddressInfoItem")
      );
      this.addFleetForm.lat = lat;
      this.addFleetForm.lng = lng;
      this.addFleetForm.address = address;
      ////console.log('看看', this.addFleetForm);
      localStorage.removeItem("fleetAddressInfoItem");
      this.$refs["addFleetForm"].clearValidate("address");

      this.VisibleMap = false;
    },

    // 清空
    CleanUp() {
      this.fleetName = "";
      this.getList(1);
    },
    changePages(val) {
      this.pageCurrent = val;
      ////console.log(val);
      this.getList();
    },
     // 记录滚动距离
     scrollEvent(res) {
      this.$route.meta.scrollTop = res.target.scrollTop
          //console.log(res.target.scrollTop);
    },
  },
  activated() {
    //组件激活时监听表格滚动条位置,
    this.$refs.table1.bodyWrapper.addEventListener('scroll',this.scrollEvent,false)
    // 激活设置滚动位置
    this.$refs.table1.bodyWrapper.scrollTop=this.$route.meta.scrollTop 
  },
  beforeRouteLeave(to, from, next) {
    // 为了节省资源，再离开页面的时候关闭对于scroll事件的监听
    this.$refs.table1.bodyWrapper.removeEventListener('scroll', this.scrollEvent)
    next()
  },
  mounted() {
    this.newCity = newCity; //存储城市数组
    this.getList();
  },
  components: {
    breadcrumb,
    applyJoin,
    leaveConfirm,
    external,
    consentFleet
  },
};
</script>

<style lang="scss" scoped>
.main {
  .mainTabs {
    ::v-deep .el-tabs__nav {
      margin-left: 38px;
    }
    ::v-deep .el-tabs__header{
      margin-bottom: 6px;
    }

    ::v-deep .el-tabs__nav-scroll {
      background-color: #fff;
    }

    // 标签页切换按钮
    ::v-deep .el-tabs__item {
      height: 50px;
      width: 88px;
      text-align: center;
      padding: 0;
      line-height: 50px;
      font-size: 12px;
      font-weight: bold;
      color: #939393;
    }

    // 下边框
    ::v-deep .el-tabs__nav-wrap::after {
      height: 1px;
      background-color: #f0f0f0;
    }

    // 标签页切换按钮 激活样式
    ::v-deep .el-tabs__item.is-active {
      background-color: #ecf5fe;
      color: #1890ff;
    }

    .main_item {
      width: 100%;
      height: calc(100vh - 182px);
      background-color: #fff;
      padding: 0px 30px 0 30px;

      .control {
        height: 76px;
        width: 100%;
        background-color: #fff;
        display: flex;
        align-items: center;

        .Btn_grounp {
          margin-left: auto;
          .searchBtn {
            width: 80px;
            height: 32px;
            color: #fff;
            font-size: 12px;
            background-color: #1890ff;
            transition: 0.2s;

            &:hover {
              opacity: 0.8;
            }
          }
        }

        .inputItem {
          display: flex;
          align-items: center;
          margin-right: 23px;

          >.title {
            color: #262626;
            font-size: 12px;
            margin-right: 7px;
          }

          >.inputBox {
            width: 160px;

            .select {
              ::v-deep .el-input__icon {
                line-height: 0;
              }
            }

            ::v-deep .el-input__inner {
              height: 32px;
              font-size: 12px;
            }

            ::v-deep .el-input__inner::placeholder {
              color: #c3c3c3;
              font-size: 12px;
            }
          }
        }
      }



      .list {
        //height: calc(100% - 50px);

        ::v-deep .el-table__body-wrapper {
          height: calc(100vh - 355px) !important;
          overflow-y: scroll;
        }

        // 表头样式
        ::v-deep .el-table__header th {
          background-color: #f0f6fd;
          color: #262626;
          font-size: 12px;
          font-weight: bold;
          text-align: center;

          // 表 body的td
          ::v-deep .el-table__body td {
            color: #595959;
            font-size: 12px;
          }
        }

        .stateBtns {
          height: 30px;

          ::v-deep .el-button {
            font-size: 12px;
            border: none;
            width: 76px;
            height: 30px;
            margin: 0 auto;
            box-sizing: border-box;
          }

          .icon-dian {
            font-size: 12px;
          }

          .Pass {
            background-color: #ecf5fe;
            color: #1890ff;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 10px 10px 9px;
          }

          .noPass {
            background-color: #fde8e9;
            color: #f7555d;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }

      .paginationBox {
        width: 100%;
        background-color: #fff;
        display: flex;
        height: 48px;
        align-items: center;

        .pagination {
          margin-left: auto;
        }
      }
    }

  }


}


.map_dialog {
  ::v-deep .el-dialog__header {
    border-bottom: 1px solid #f0f0f0;
    color: #262626;
    font-size: 14px;
    height: 50px;
    display: flex;
    align-items: center;
    font-weight: bold;
  }

  //关闭图标
  ::v-deep .el-dialog__headerbtn .el-dialog__close {
    font-size: 15px;
  }

  ::v-deep .el-dialog__body {
    padding: 6px 7px;
  }

  .mapBox {
    display: flex;
    flex-direction: column;
    align-items: center;

    .addMapBox {
      margin-bottom: 15px;

      .map {
        width: 486px;
        height: 372px;
      }
    }
  }
}

.addFleetFormStyle {
  ::v-deep .el-form-item__label {
    color: #262626;
    font-size: 12px;
  }
}
</style>

<style lang="scss">
.supplier_Zdydialog .dialog_BtnGroup {
  width: 100%;
  display: flex;
  justify-content: flex-end;

  >.cancelBtn {
    width: 80px;
    height: 32px;
    line-height: 0px;
    border: 1px solid #d9d9d9;
    color: #262626;
    font-size: 12px;
    border-radius: 4px;
    background-color: #fff;
    transition: 0.2s;

    &.hover {
      opacity: 0.8;
    }
  }

  >.submitBtn {
    background-color: #1890ff;
    width: 80px;
    height: 32px;
    line-height: 0px;
    color: #fff;
    border-radius: 4px;
    font-size: 12px;
    transition: 0.2s;

    &.hover {
      opacity: 0.8;
    }
  }
}
</style>
